package com.filetransfer.app.db;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;
public class HistoryDatabaseHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "history.db";
    private static final int DATABASE_VERSION = 1;
    // SQL 创建表语句
    private static final String CREATE_TABLE = "CREATE TABLE if not exists history ("
            + "_id INTEGER PRIMARY KEY AUTOINCREMENT,"
            + "uri TEXT,"
            + "fileName TEXT,"
            + "code TEXT,"
            + "message TEXT,"
            + "time TEXT);";
    public HistoryDatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE); // 创建表
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 如果需要升级数据库
        db.execSQL("DROP TABLE IF EXISTS history");
        onCreate(db);
    }
    public void deleteAll() {
        SQLiteDatabase db = getWritableDatabase();
        db.execSQL("DELETE FROM history");
    }
    public void deleteById(int id) {
        SQLiteDatabase db = getWritableDatabase();
        db.execSQL("DELETE FROM history WHERE _id = ?", new String[]{String.valueOf(id)});
    }
    public void insert(String uri, String fileName, String code, String message, String time) {
        SQLiteDatabase db = getWritableDatabase();
        db.execSQL("INSERT INTO history (uri, fileName, code, message, time) VALUES (?, ?, ?, ?, ?)",
                new String[]{uri, fileName, code, message, time});
    }
    public record  History(int id, String uri, String fileName, String code, String getStatus,
                          String time) {
    }
    public List<History> queryAll() {
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT * FROM history", null);
        List<History> list = new ArrayList<>();
        while (cursor.moveToNext()) {
            int id = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
            String uri = cursor.getString(cursor.getColumnIndexOrThrow("uri"));
            String fileName = cursor.getString(cursor.getColumnIndexOrThrow("fileName"));
            String code = cursor.getString(cursor.getColumnIndexOrThrow("code"));
            String message = cursor.getString(cursor.getColumnIndexOrThrow("message"));
            String time = cursor.getString(cursor.getColumnIndexOrThrow("time"));
            list.add(new History(id, uri, fileName, code, message, time));
        }
        cursor.close();
        return list;
    }
}
